// pages/market/market.js
const { formatDate } = require('../../utils/util.js');

Page({
  /**
   * 页面的初始数据
   */
  data: {
    year: '',
    month: '',
    day: '',
    weekDay: '',
    // 移除假数据
    // stocks: [], // 移除硬编码的 stocks 数组
    selectedStocks: [], // 新增用于存储用户自选股的实时数据
    isLoggedIn: false, // 新增登录状态标志
    showAuthMessage: false, // 新增用于控制是否显示"授权同步自选股"消息
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    const currentDate = new Date();
    const formattedDate = formatDate(currentDate);

    this.setData({
      year: formattedDate.year,
      month: formattedDate.month,
      day: formattedDate.day,
      weekDay: formattedDate.weekDay,
      // stocks // 移除更新 stocks 的逻辑
    });

    // 在 onLoad 中不加载数据，改在 onShow 中检查登录状态并加载自选股
    // this.loadSelectedStocks(); 
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    // 页面显示时检查登录状态并加载自选股
    this.checkLoginStatusAndLoadStocks();
  },

  // Helper method to format volume (copied from index.js)
  formatVolume: function(num) {
    if (num === undefined || num === null) return '0';

    num = parseFloat(num);
    if (isNaN(num)) return '0';

    if (num >= 100000000) {
      return (num / 100000000).toFixed(2) + '亿';
    } else if (num >= 10000) {
      return (num / 10000).toFixed(2) + '万';
    } else {
      return num.toFixed(0);
    }
  },

  // Method to fetch and parse stock real-time data for a list of codes (copied from index.js)
  async fetchAndParseStockData(codes) {
    console.log('Market page: fetchAndParseStockData input codes:', codes);
    if (!codes || codes.length === 0) {
      console.log('Market page: fetchAndParseStockData received empty codes array');
      return [];
    }

    const fullCodes = codes.map(code => {
      // Assuming codes from getUserSelectedStocks are pure numbers
      const prefix = code.startsWith('6') ? 'sh' : 'sz';
      return prefix + code;
    }).join(',');

    console.log('Market page: Sina API full codes string:', fullCodes);

    return new Promise((resolve, reject) => {
      wx.request({
        url: `https://hq.sinajs.cn/list=${fullCodes}`,
        header: {
          'content-type': 'application/json',
          'Referer': 'https://finance.sina.com.cn'
        },
        success: (res) => {
          console.log('Market page: Sina API raw response:', res.data);
          if (res.data) {
            const results = res.data.split(';').filter(item => item.includes('var hq_str_')).map(item => {
              try {
                const dataStr = item.split('="')[1].split('";')[0];
                const elements = dataStr.split(',');
                console.log('Market page: Parsing item:', item, 'elements:', elements);

                if (elements.length > 1) { // Basic check for valid data
                   // Calculate change and change percent
                  const currentPrice = parseFloat(elements[3]);
                  const yesterdayClose = parseFloat(elements[2]);
                  const priceChange = (currentPrice - yesterdayClose);
                  const changePercent = ((priceChange / yesterdayClose) * 100);

                  // Extract pure numeric code, removing prefix if present in the response string
                  const rawCodeInResponse = item.split('="')[0].replace('var hq_str_', '');
                  const code = rawCodeInResponse.replace(/[^\d]/g, ''); // Ensure only digits

                  return {
                    // Extract code without prefix
                    // code: item.split('="')[0].replace('var hq_str_', '').substring(2), // Original parsing logic
                    code: code, // Use the cleaned up code
                    name: elements[0],
                    price: currentPrice,
                    currentPrice: currentPrice.toFixed(2), // Formatted price
                    change: priceChange, // Raw change
                    priceChange: priceChange > 0 ? '+' + priceChange.toFixed(2) : priceChange.toFixed(2), // Formatted change
                    changePercent: changePercent, // Raw change percent
                    changePercent: changePercent > 0 ? '+' + changePercent.toFixed(2) + '%' : changePercent.toFixed(2) + '%', // Formatted change percent
                    volume: this.formatVolume(parseFloat(elements[8]) / 100), // Formatted volume
                    amount: parseFloat(elements[9]), // Raw amount
                  };
                } else {
                   console.log('Market page: Skipping item with insufficient elements:', item);
                }
              } catch (e) {
                 console.error('Market page: 解析股票数据出错:', e, 'data:', item);
              }
              return null;
            }).filter(item => item !== null);
            
            console.log('Market page: 解析后的股票数据:', results);
            resolve(results);
          } else {
            console.log('Market page: Sina API returned no data');
            resolve([]); // Resolve with empty array if no data
          }
        },
        fail: (err) => {
          console.error('Market page: 获取股票数据失败:', err);
          reject(err);
        }
      });
    });
  },

  // Method to check login status and load selected stocks
  async checkLoginStatusAndLoadStocks() {
    // Simpler login check for now (can be replaced with cloud function call if needed)
    // const isLoggedIn = wx.getStorageSync('isLoggedIn'); // Remove local storage check
    
    let isLoggedIn = false; // Default to not logged in
    const userInfo = wx.getStorageSync('userInfo'); // Get user info from local storage

    if (userInfo && userInfo.phone && userInfo.openid) {
       console.log('Market page: Found userInfo in local storage, checking status via cloud function');
       try {
          const { result } = await wx.cloud.callFunction({
            name: 'user',
            data: {
              type: 'checkStatus',
              phone: userInfo.phone,
            }
          });
          console.log('Market page: checkStatus cloud function result:', result);
          if (result.success && result.isLoggedIn) {
            isLoggedIn = true;
          }
       } catch (error) {
         console.error('Market page: Error checking login status via cloud function:', error);
         // If cloud function fails, assume not logged in
         isLoggedIn = false;
       }
    } else {
      console.log('Market page: No valid userInfo in local storage, user is not logged in');
      isLoggedIn = false;
    }

    this.setData({
      isLoggedIn: isLoggedIn,
      showAuthMessage: !isLoggedIn, // 如果未登录，显示授权消息
      selectedStocks: [] // 清空之前的自选股数据
    });

    if (isLoggedIn) {
      wx.showLoading({
        title: '加载自选股...'
      });
      try {
        // Call cloud function to get user selected stock codes
        const { result } = await wx.cloud.callFunction({
          name: 'user',
          data: {
            type: 'getUserSelectedStocks' // Corrected parameter name
          }
        });

        console.log('getUserSelectedStocks cloud function result:', result);

        if (result && result.success && result.stockCodes && result.stockCodes.length > 0) {
          // Fetch real-time data for the selected stock codes
          const realTimeStocks = await this.fetchAndParseStockData(result.stockCodes);
          console.log('Fetched real time stocks:', realTimeStocks);

          // Update data with real-time stock info
          this.setData({
            selectedStocks: realTimeStocks
          });
        } else {
           // If no selected stocks or cloud function fails, clear selected stocks
           this.setData({
             selectedStocks: []
           });
           if(result && !result.success) { // Show error if cloud function failed
             wx.showToast({ title: '获取自选股失败', icon: 'none' });
           }
        }
      } catch (error) {
        console.error('加载自选股数据失败:', error);
        wx.showToast({
          title: '加载自选股失败',
          icon: 'none',
        });
         this.setData({
            selectedStocks: []
           });
      } finally {
        wx.hideLoading();
      }
    }
  },

  /**
   * 跳转到登录页面
   */
  navigateToLogin() {
    wx.navigateTo({
      url: '/pages/login/login'
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
     // Allow pull down to refresh selected stocks if logged in
     if(this.data.isLoggedIn) {
        this.checkLoginStatusAndLoadStocks().then(() => {
            wx.stopPullDownRefresh(); // Stop refresh animation after loading
        }).catch(() => {
            wx.stopPullDownRefresh(); // Stop animation even if failed
        });
     } else {
        wx.stopPullDownRefresh(); // Stop animation if not logged in
     }
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },

  // 跳转到个股详情页面
  navigateToStockDetail(e) {
    const { name, code } = e.currentTarget.dataset;
    wx.navigateTo({
      url: `/pages/stock-detail/index?name=${name}&code=${code}`
    });
  }
})